package prassein.rsm.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import jxl.write.WriteException;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.beans.factory.annotation.Autowired;

import prassein.rsm.common.utils.Constants;
import prassein.rsm.common.utils.UploadConfigurationRead;
import prassein.rsm.common.utils.WriteExcel;
import prassein.rsm.dto.DownloadChoice;
import prassein.rsm.dto.FilterDto;
import prassein.rsm.entity.base.Resume;
import prassein.rsm.service.base.AuditManager;
import prassein.rsm.service.base.ResumeManager;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Results({
	@Result(name = "success",location="resumeList.jsp"), 
	@Result(name = "error",location="login.jsp"),
	@Result(name = "input",location="resumeInsert.jsp")})
public class ResumeListAction extends ActionSupport implements ServletContextAware{
	
	private static SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
	
	@Autowired
	private ResumeManager resumeManager;
	
	@Autowired
	private AuditManager auditManager;
	
	private static final long serialVersionUID = -7416211125815929519L;
	
	private ServletContext context;
	
	private long resumeId = -1;
	
	public int totalCount = 0;
	
	private int isSearchMode;
	private int isWriteXlsMode;
	private int isNormalMode;
	
	private FilterDto filterResume = new FilterDto();

	private String xlsFileLocatoin;
	
	private List<Resume> resumeList;
	
	private DownloadChoice filter = new DownloadChoice();
	
	public List<Resume> getResumeList() {
		return resumeList;
	}
	public void setResumeList(List<Resume> resumeList) {
		this.resumeList = resumeList;
	}
	
	@Override 
	public String execute() throws Exception {
		initEvn();
		
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get(Constants.USERNAME) != null && !session.get(Constants.USERNAME).equals("")) {
			String res = SUCCESS;
			
			if (isWriteXlsMode == 1) {
				res = ListSearchResume(session, filterResume);
				writeXls(filter);
				auditManager.save(session.get(Constants.USERNAME).toString(), "导出", "");
			} else if (isSearchMode == 1) {
				res = ListSearchResume(session, filterResume);
			} else if (isNormalMode == 1) {
				res = ListAllResume(session);
			}
			
			cleanEvn();
			return res;
		} else {
			cleanEvn();
			return ERROR;
		}
	}
	
	private void writeXls(DownloadChoice filter) {
		WriteExcel test = new WriteExcel(resumeList);
		test.setFilter(filter);
		
		String targetDirectory = context.getRealPath("");
		
		Calendar calendar = Calendar.getInstance();
		xlsFileLocatoin = UploadConfigurationRead.getInstance().getConfigItem("xlsTempFolder").trim() + "/" + calendar.get(Calendar.YEAR) + "_" 
				+ (calendar.get(Calendar.MONTH) + 1) + "_"
				+ calendar.get(Calendar.DAY_OF_MONTH) + "_"
				+ calendar.get(Calendar.HOUR_OF_DAY) + "_"
				+ calendar.get(Calendar.MINUTE) + "_"
				+ calendar.get(Calendar.SECOND) + ".xls";
		
        test.setOutputFile(targetDirectory + "/" + xlsFileLocatoin);
        
        try {
			test.write();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private String ListSearchResume(Map<String, Object> session, FilterDto filterResume) {
		List<Resume> resumeListTemp = resumeManager.queryResult(filterResume);
		resumeList = new ArrayList<Resume>();
		
		java.util.Date date = new Date();
		for (Resume item : resumeListTemp) {
			try {
				String ageStr = GetAge(date, item);
				if (IsInAgeRole(filterResume.getAge1(), filterResume.getAge2(), ageStr)) {
					item.setDateOfBirth(ageStr + "岁");
					resumeList.add(item);
				}
			} catch (Exception e) {
				
			}
		}
		
		return SUCCESS;
	}
	
	private boolean IsInAgeRole(String age1, String age2, String ageStr) {
		int age = Integer.parseInt(ageStr);
		
		boolean res1 = false;
		boolean res2 = false;
		
		if (age2 != null && !age2.trim().equals("")) {
			res2 = age <= Integer.parseInt(age2.trim());
		} else {
			res2 = true;
		}
		
		if (age1 != null && !age1.trim().equals("")) {
			res1 = age >= Integer.parseInt(age1.trim());
		} else {
			res1 = true;
		}
		
		return res1 && res2;
	}
	
	private String ListAllResume(Map<String, Object> session) {
		List<Resume> resumeListTemp = resumeManager.getResumes();
		
		totalCount = resumeListTemp.size();
		
		java.util.Date date = new Date();
		for (Resume item : resumeListTemp) {
			try {
				item.setDateOfBirth(GetAge(date, item) + "岁");
			} catch (Exception e) {
				
			}
		}
		resumeList = resumeListTemp;
		session.remove(Constants.LATEST_EDIT_REUMEID);
		
		return SUCCESS;
	}
	
	private String GetAge(java.util.Date date, Resume item) throws ParseException {
		java.util.Date mydate = myFormatter.parse(item.getDateOfBirth());
		long day = (date.getTime()-mydate.getTime())/(24*60*60*1000) + 1;
		String year = new java.text.DecimalFormat("#").format(day/365f);
		return year;
	}
	
	private void initEvn() {
		xlsFileLocatoin = "";
	}
	private void cleanEvn() {
		resumeId = -1;
		isSearchMode = 0;
		isWriteXlsMode = 0;
		isNormalMode = 0;
	}
	
	public ResumeManager getResumeManager() {
		return resumeManager;
	}
	public void setResumeManager(ResumeManager resumeManager) {
		this.resumeManager = resumeManager;
	}
	public long getResumeId() {
		return resumeId;
	}
	public void setResumeId(long resumeId) {
		this.resumeId = resumeId;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public String getXlsFileLocatoin() {
		return xlsFileLocatoin;
	}
	public void setXlsFileLocatoin(String xlsFileLocatoin) {
		this.xlsFileLocatoin = xlsFileLocatoin;
	}
	@Override
	public void setServletContext(ServletContext context) {
		this.context = context;
	}
	public DownloadChoice getFilter() {
		return filter;
	}
	public void setFilter(DownloadChoice filter) {
		this.filter = filter;
	}
	public int getIsSearchMode() {
		return isSearchMode;
	}
	public void setIsSearchMode(int isSearchMode) {
		this.isSearchMode = isSearchMode;
	}
	public int getIsWriteXlsMode() {
		return isWriteXlsMode;
	}
	public void setIsWriteXlsMode(int isWriteXlsMode) {
		this.isWriteXlsMode = isWriteXlsMode;
	}
	public int getIsNormalMode() {
		return isNormalMode;
	}
	public void setIsNormalMode(int isNormalMode) {
		this.isNormalMode = isNormalMode;
	}
	public AuditManager getAuditManager() {
		return auditManager;
	}
	public void setAuditManager(AuditManager auditManager) {
		this.auditManager = auditManager;
	}
	public FilterDto getFilterResume() {
		return filterResume;
	}
	public void setFilterResume(FilterDto filterResume) {
		this.filterResume = filterResume;
	}
}
